import 'dart:io';

import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_payment_singleton.dart';
import 'package:xindong/models/xindong_recharge_class.dart';

class XinDongRechargeCtr extends GetxController {
  static XinDongRechargeCtr get to => Get.find();

  List<XinDongRechargeClass> dataList = [];
  XinDongRechargeClass? selectClass; //当前选择的model
  int? paymentMethod = PaymentMethod.ant; //当前选择的支付方式

  bool isSelectClass(XinDongRechargeClass selectClass) {
    return this.selectClass?.id == selectClass.id;
  }

  bool isSelectWay(int selectWay) {
    return paymentMethod == selectWay;
  }

  // 1、选择项目
  void setSelectClass(XinDongRechargeClass selectClass) {
    this.selectClass = selectClass;
    update(["model"]);
  }

  // 2、选择方式
  void setSelectWay(int method) {
    paymentMethod = method;
    update(["method"]);
  }

  // 3、调起支付
  void onTapBuy({Function(XinDongRechargeClass model, int selectWay)? onTapRecharge}) async {
    if (selectClass == null) {
      showToast("请选择充值面额");
      return;
    }
    if (paymentMethod == null && !Platform.isIOS) {
      showToast("请选择支付方式");
      return;
    }
    if (onTapRecharge == null) {
      XinDongPaymentSingleton.instance.buyRecharge(selectClass!, paymentMethod!);
    } else {
      onTapRecharge(selectClass!, paymentMethod!);
    }
  }

  // 列表
  Future requestGetList() async {
    _setupDefaultClass();
    final object = await XinDongNetworking.instance.request(
      XinDongApi.rechargeList,
      method: XinDongHttpMethod.post,
    );
    if (object.code == XinDongServerStatus.success) {
      List list = object.data;
      dataList = list.map((e) => XinDongRechargeClass.fromJson(e)).toList();
      update();
    }
    _setupDefaultClass();
    return Future.value();
  }

  // 设置默认选项
  void _setupDefaultClass() {
    if (selectClass == null && dataList.isNotEmpty) {
      setSelectClass(dataList.first);
    }
  }
}
